import { Controller } from 'egg'

class DefaultController extends Controller {
  async online() {
    const { ctx } = this
    let nspName = '/'
    if (ctx.params.id) {
      nspName = `/${ctx.params.id}`
    }
    const nsp = this.app.io.of(nspName)
    // this.logger.info('online', nsp.name)

    const results = await new Promise((resolve, reject) => {
      nsp.clients((error, clients) => {
        if (error) reject(error)
        this.logger.info('io/controller/default nps.clients', clients)
        resolve(clients)
      })
    })
    ctx.body = results
  }

  async test() {
    const { ctx } = this
    const logFormat = `io/controller/default/test id: %s
    args: %j
    header: %j
    query: %j
    user: %j
    socket keys: %j`
    this.logger.info(logFormat, ctx.args, ctx.header, ctx.query, ctx.state.user, Object.keys(ctx.socket))
    await ctx.socket.emit('test', `test args ${ctx.args}`)
  }

  async message() {
    const { ctx } = this
    // this.logger.info('message', ctx.args, ctx.socket.id)
    await ctx.socket.emit('message', `message args ${ctx.args}`)
  }
}

export default DefaultController
